package com.nationart.backend.controller;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nationart.backend.util.Response;
import com.nationart.backend.util.ShiroUtils;

@Controller
public class SysLoginController {
	private Logger log = LoggerFactory.getLogger(SysUserController.class);
	@RequestMapping("/signin")
	public String signin() {
		return "login";
	}
	
	
	@ResponseBody
	@PostMapping("/login")
	public Response login(String username, String password){
		log.debug("login");
		if(username == null || password == null) {
			return Response.error("用户名或密码不能为空");
		}
		
		Subject subject = ShiroUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			subject.login(token);
			return Response.ok("登录成功");
		}catch(UnknownAccountException e) {
			return Response.error(e.getMessage());
		}catch(LockedAccountException e) {
			return Response.error(e.getMessage());
		}catch( AuthenticationException e) {
			return Response.error("用户名或密码错误");
		}
	}
}
